import { Buffer } from 'buffer'
import process from 'process'

async function setupPolyfills() {
  try {
    const cryptoModule = await import('crypto-browserify')
    const streamModule = await import('stream-browserify')
    
    Object.defineProperty(window, 'crypto', {
      value: {
        subtle: cryptoModule.subtle
      },
      configurable: true,
      writable: true
    });
    
    window.crypto = cryptoModule.default
    window.stream = streamModule.default
    window.global.crypto = cryptoModule.default
    window.global.stream = streamModule.default

  } catch (error) {
    console.error('Failed to load polyfills:', error);
  }
}

if (typeof window !== 'undefined') {
  window.Buffer = Buffer
  window.process = process
  window.global = window
  window.global.Buffer = Buffer
  window.global.process = process
  
  // 调用异步函数设置polyfills
  setupPolyfills()
}